import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_time_manager/pages/add_todo_page.dart';
import 'package:flutter_time_manager/state/model/todo.dart';
import 'package:flutter_time_manager/state/time_manager_state.dart';
import 'package:flutter_time_manager/state/user_state.dart';
import 'package:flutter_time_manager/widget/dashed_widget.dart';
import 'package:flutter_time_manager/widget/my_avatar_widget.dart';
import 'package:flutter_time_manager/widget/todo_collect_item_widget.dart';
import 'package:provider/provider.dart';

class TodoListPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              expandedHeight: 170.0,
              flexibleSpace: FlexibleSpaceBar(
                background: Container(
                  padding: const EdgeInsets.only(left: 20.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      const SizedBox(height: 20.0),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Consumer<UserState>(
                            builder: (context, userState, _) => GestureDetector(
                                  onTap: () => userState.replaceImage(),
                                  child: MyAvatarWidget(
                                      imgPath: userState.avatarImageFilePath),
                                ),
                          ),
                          IconButton(
                              icon: Icon(Icons.settings),
                              onPressed: () => Navigator.of(context)
                                  .pushNamed("/SettingPage")),
                        ],
                      ),
                      const SizedBox(height: 10.0),
                      Consumer<UserState>(
                        builder: (context, userState, _) => InkWell(
                              onTap: () async {
                                String nickName = await _asyncInputDialog(
                                    context, userState.userName, 15);
                                userState.updateName(nickName);
                              },
                              child: Text(
                                userState.isLoading
                                    ? "..."
                                    : userState.userName,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 24.0),
                              ),
                            ),
                      ),
                      const SizedBox(height: 5.0),
                      Consumer<UserState>(
                        builder: (context, userState, _) => InkWell(
                              onTap: () async {
                                String note = await _asyncInputDialog(
                                    context, userState.note, 25);
                                userState.updateNote(note);
                              },
                              child: Text(
                                userState.isLoading ? "..." : userState.note,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12.0, color: Colors.grey),
                              ),
                            ),
                      ),
                      const SizedBox(height: 16.0),
                    ],
                  ),
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Consumer<TimeManager>(
                builder: (context, manager, _) => manager.isLoading
                    ? _loadingWidget()
                    : CarouselSlider(
                        items: manager.todoCollectList
                            .map((item) => TodoCollectItemWidget(
                                key: Key(item.id), todoCollect: item))
                            .toList(),
                        autoPlay: false,
                        enlargeCenterPage: true,
                        viewportFraction: 0.90,
                        aspectRatio: 2.0,
                        enableInfiniteScroll: false,
                        onPageChanged: (index) =>
                            manager.setCurrentCollect(index),
                      ),
              ),
            ),
            const SliverToBoxAdapter(
              child: SizedBox(height: 20.0),
            ),
            SliverToBoxAdapter(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(left: 23.0),
                    child: Text("待办事项",
                        style: TextStyle(
                            fontSize: 16.0, fontWeight: FontWeight.bold)),
                  ),
                  Consumer<TimeManager>(
                    builder: (context, manager, _) => IconButton(
                          icon: Icon(Icons.add_circle_outline),
                          onPressed: () => Navigator.of(context).pushNamed(
                              "/AddTodoPage",
                              arguments: [manager.currentCollect.id]),
                        ),
                  ),
                ],
              ),
            ),
            const SliverToBoxAdapter(
              child: SizedBox(height: 20.0),
            ),
            Consumer<TimeManager>(
              builder: (context, manager, _) => manager.isLoading
                  ? SliverToBoxAdapter(child: _loadingWidget())
                  : _TodoListWidget(context, manager),
            ),
          ],
        ),
      ),
    );
  }

  Future<String> _asyncInputDialog(
      BuildContext context, String nickName, int maxLength) async {
    return showDialog<String>(
      context: context,
      barrierDismissible: true,
      // dialog is dismissible with a tap on the barrier
      builder: (BuildContext context) {
        return AlertDialog(
          content: Row(
            children: <Widget>[
              Expanded(
                  child: TextField(
                autofocus: true,
                maxLength: maxLength,
                decoration: InputDecoration(hintText: nickName),
                onChanged: (value) {
                  nickName = value;
                },
              ))
            ],
          ),
          actions: <Widget>[
            FlatButton(
              child: const Text('保存'),
              onPressed: () {
                Navigator.of(context).pop(nickName);
              },
            ),
          ],
        );
      },
    );
  }

  Widget _loadingWidget() {
    return Center(
      child: SizedBox(
        width: 30.0,
        height: 30.0,
        child: CircularProgressIndicator(),
      ),
    );
  }

  SliverList _TodoListWidget(BuildContext context, TimeManager manager) {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return TodoItem(
            key: Key(manager.getTodo(index).id),
            currentCollectId: manager.currentCollect.id,
            todo: manager.getTodo(index),
            isLast: (manager.getTodoSize() - 1) == index,
            deleteHandler: manager.deleteTodo,
          );
        },
        childCount: manager.getTodoSize(),
      ),
    );
  }
}

const afterColor = Color(0xff979797);
const beforeColor = Color(0xff4a8ede);

class TodoItem extends StatelessWidget {
  final String currentCollectId;
  final Todo todo;

  final bool isLast;
  final ValueSetter<String> deleteHandler;

  const TodoItem(
      {Key key,
      this.currentCollectId,
      this.todo,
      this.isLast,
      this.deleteHandler})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final query = MediaQuery.of(context);
    final afterFlag = DateTime.now().isAfter(todo.taskTime);
    final colorFont = afterFlag ? Colors.black : afterColor;
    return InkWell(
      onLongPress: () async {
        bool isDelete = await _deleteDialog(context);
        if (isDelete != null && isDelete) {
          deleteHandler(todo.id);
        }
      },
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) {
              return AddTodoPage(todo: todo);
            },
            settings: RouteSettings(arguments: [currentCollectId])));
      },
      child: Container(
          height: 60.0,
          padding: const EdgeInsets.only(left: 20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                height: 20.0,
                child: Row(
                  children: <Widget>[
                    Icon(
                        afterFlag
                            ? Icons.check_circle
                            : Icons.radio_button_checked,
                        color: afterFlag ? beforeColor : afterColor,
                        size: 18.0),
                    const SizedBox(width: 16.0),
                    Text(todo.taskTimeToLocal,
                        style: TextStyle(fontSize: 14.0, color: colorFont)),
                    const SizedBox(width: 26.0),
                    Container(
                      width: query.size.width - 100 - 60,
                      child: Text("${todo.title}",
                          style: TextStyle(fontSize: 14.0, color: colorFont),
                          overflow: TextOverflow.ellipsis),
                    ),
                  ],
                ),
              ),
              isLast
                  ? const SizedBox(width: 0.0, height: 0.0)
                  : const DashedWidget(height: 40.0),
            ],
          )),
    );
  }

  Future<bool> _deleteDialog(BuildContext context) async {
    return showDialog<bool>(
        context: context,
        barrierDismissible: true,
        // dialog is dismissible with a tap on the barrier
        builder: (BuildContext context) {
          return AlertDialog(
            content: Text("是否删除"),
            actions: <Widget>[
              FlatButton(
                child: const Text('删除'),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
              FlatButton(
                child: const Text('返回'),
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
              ),
            ],
          );
        });
  }
}

final List<String> products =
    List.generate(30, (index) => "Hello World Index: ${index}");
